package cn.ixinjiu.libraryMangement.controller.admin.borrow;

import cn.ixinjiu.libraryMangement.dao.IBookInfoDao;
import cn.ixinjiu.libraryMangement.dao.IBorrowInfoDao;
import cn.ixinjiu.libraryMangement.dao.impl.BookInfoDaoImpl;
import cn.ixinjiu.libraryMangement.dao.impl.BorrowInfoDaoImpl;
import cn.ixinjiu.libraryMangement.entity.BookInfo;
import cn.ixinjiu.libraryMangement.entity.BorrowInfo;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;

/**
 * Created by XinChen on 2023-06-28
 *
 * @TODO 借阅图书： 1.新增借阅信息  2. 修改图书状态
 */
@WebServlet("/adminBorrowInfoAdd")
public class BorrowInfoAddServlet extends HttpServlet {
    private IBorrowInfoDao iBorrowInfoDao = new BorrowInfoDaoImpl();
    private IBookInfoDao iBookInfoDao = new BookInfoDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Type", "text/html;charset=utf-8");

        // 获取前端参数
        int userId = Integer.valueOf(req.getParameter("user_id"));
        int bookId = Integer.valueOf(req.getParameter("book_id"));
        Date borrowDate = Date.valueOf(req.getParameter("borrow_date"));
        Date returnDate = Date.valueOf(req.getParameter("return_date"));
        BorrowInfo borrowInfo = new BorrowInfo(null, userId, bookId, borrowDate, returnDate, null, 0, 0, 0);
        // 调用新增方法
        int add = iBorrowInfoDao.borrowAdd(borrowInfo);
        // 修改图书状态
        BookInfo bookInfoById = iBookInfoDao.getBookInfoById(bookId);
        bookInfoById.setStatus(1);
        int update = iBookInfoDao.bookInfoUpd(bookInfoById);
        // 返回数据
        JSONObject json = new JSONObject();
        if (add == 1 && update == 1) {
            json.put("code", "0");
            json.put("msg", "借阅成功");
        } else {
            json.put("code", "1");
            json.put("msg", "借阅失败");
        }
        // 输出到页面
        PrintWriter writer = resp.getWriter();
        writer.write(json.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
